import {JSEncrypt} from 'jsencrypt'
import {b64tohex, hextob64, KJUR} from 'jsrsasign'

/**
 * 加密
 * @param pubKey 公钥
 * @param plain 明文
 * @returns {*} 加密结果
 */
export function RSAEncrypt(pubKey, plain) {
    // eslint-disable-next-line no-undef
    let jse = new JSEncrypt()
    jse.setPublicKey(pubKey)
    return jse.encrypt(plain)
}

/**
 * 解密
 * @param prvKey 密钥
 * @param cipher 密文
 * @returns {*} 解密结果
 */
export function RSADecrypt(prvKey, cipher) {
    console.log(cipher)

    // eslint-disable-next-line no-undef
    let jse = new JSEncrypt()
    jse.setPrivateKey(prvKey)

    console.log(jse)
    return jse.decrypt(cipher)
}

/**
 * 加签
 * @param prvKey 私钥
 * @param plain 明文
 * @returns {string|*} 加签结果
 */
export function RSASignature(prvKey, plain) {
    // eslint-disable-next-line no-undef
    /*let sig = new KJUR.crypto.Signature({"alg": "SHA1withRSA", "prov": "cryptojs/jsrsa", "prvkeypem": prvKey})
    let hashAlg = 'sha1'
    // 加签
    let sign = sig.signString(plain, hashAlg)
    sign = hex2b64(sign)
    return sign*/

    let signature = new KJUR.crypto.Signature({alg: "SHA1withRSA"})
    signature.init(prvKey)
    signature.updateString(plain)
    let a = signature.sign()
    return hextob64(a)
}

/**
 * 解签
 * @param pubKey 公钥
 * @param originData 原始值
 * @param data 待验证数据
 * @returns {*} 解签结果
 */
export function RSAVerify(pubKey, originData, data) {
    /*try {
        let sig = new KJUR.crypto.Signature({"alg": "SHA1withRSA", "prov": "cryptojs/jsrsa", "prvkeypem": pubKey})
        sig.updateString(originData)
        // 将Base64转为16进制
        data = b64tohex(data)
        // 验签
        return sig.verify(data)
    } catch (e) {
        console.error(e)
    }*/
    let signatureVf = new KJUR.crypto.Signature({alg: "SHA1withRSA", prvkeypem: pubKey})
    signatureVf.updateString(originData)
    return signatureVf.verify(b64tohex(data))
}
